package com.atguigu.com.nio.nio_3_selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author: robert.song
 * @Date: Created in 2021/8/8
 */
public class ServletClient {
    public static void main(String[] args) throws IOException {
        //        创建ServerSocketChannel -> ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//        得到一个Selector对象
        Selector selector = Selector.open();
//        绑定一个端口6666，在服务器端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
//        设置为非阻塞
        serverSocketChannel.configureBlocking(false);
//        把serverSocketChannel注册到selector ，关心事件为OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

//        循环等待客户端连接
        while (true) {
            System.out.println("查看有无事件发生");
            if (selector.select(1000) == 0) {
                System.out.println("无任何事件，不再等待我干别的去");
                System.out.println("......");
                System.out.println("干完了再去看看");
                continue;
            }
//            如果返回值>0，就获取到相关的selectionKey集合
//            1.如果返回的>0,表示已经获取到关注的事件
//            2.selector.selectedKeys() 返回关注事件的集合
//            3.通过selectionKeys 反向获取通道
            Set<SelectionKey> selectionKeySet = selector.selectedKeys();
//            遍历
            Iterator<SelectionKey> keyIterator = selectionKeySet.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
//                    将SocketChannel设置为非阻塞
                    socketChannel.configureBlocking(false);
                    System.out.println("连接成功，socketChannel生成：" + socketChannel.hashCode());
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) {
//                    通过key 反向获取到对应channel
                    SocketChannel channel = (SocketChannel) key.channel();
//                    获取到该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("form 客户端 " + new String(buffer.array()));

                }
//                手动从集合中移除当前的selectionKey,防止重复操作
                keyIterator.remove();
            }
        }
    }
}
